#!/bin/bash 本地传输到远端jar包并使用docker方式启动

# 源文件路径
SOURCE_PATTERN="../../../target/boot-*.jar"
# 目标用户
TARGET_USER="agilerobots"
# 目标主机
TARGET_HOST="10.8.7.30"
# 目标路径
TARGET_PATH="~/docker/java"
# 目标脚本
TARGET_SCRIPT="/home/agilerobots/docker/boot_start.sh"

# 提示用户输入密码
read -s -p "Enter password for ${TARGET_USER}@${TARGET_HOST}: " PASSWORD
echo

matching_files=($(ls $SOURCE_PATTERN 2>/dev/null))
if [ ${#matching_files[@]} -eq 0 ]; then
    echo "Error: No files found matching the pattern $SOURCE_PATTERN."
    exit 1
fi

for file in "${matching_files[@]}"; do
    if [ -f "$file" ]; then
        echo "Transferring $file..."
        sshpass -p "$PASSWORD" scp "$file" "${TARGET_USER}@${TARGET_HOST}:${TARGET_PATH}"
        if [ $? -ne 0 ]; then
            echo "Error: Failed to transfer $file."
            exit 1
        fi
    else
        echo "Warning: $file is not a regular file, skipping."
    fi
done

echo "files transferred successfully."

# 检查远程脚本是否存在
if ! sshpass -p "$PASSWORD" ssh ${TARGET_USER}@${TARGET_HOST} "[ -f ${TARGET_SCRIPT} ]"; then
    echo "Error: Remote script ${TARGET_SCRIPT} does not exist."
    exit 1
fi

# 执行远程脚本
echo "Starting remote script on ${TARGET_HOST}..."
sshpass -p "$PASSWORD" ssh ${TARGET_USER}@${TARGET_HOST} "bash ${TARGET_SCRIPT}"

# 检查ssh命令是否成功
if [ $? -ne 0 ]; then
    echo "Error: Failed to execute remote script."
    exit 1
else
    echo "Remote script executed successfully."
fi